package com.matrix.framework.core.loader.impl;

import com.matrix.framework.core.component.Jwt;
import com.matrix.framework.core.loader.ILoader;
import com.matrix.framework.sysconfig.token.service.SysConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

/**
 * JWT配置加载器
 * 
 * Copyright © 海平面工作室 版权所有
 *
 * @Author: Leo
 * @Create: 2025/06/23 23:25
 * @Since 1.2
 */
@Service
@Order(0) // 高优先级，确保JWT配置优先加载
public class JWTLoader implements ILoader {

    private static final Logger logger = LoggerFactory.getLogger(JWTLoader.class);

    private final SysConfigService sysConfigService;

    public JWTLoader(SysConfigService sysConfigService) {
        this.sysConfigService = sysConfigService;
    }

    @Override
    public String getServiceName() {
        return "JWT配置服务";
    }

    @Override
    public Mono<Void> load() {
        logger.info("开始加载JWT配置...");
        
        return loadJwtExpiration()
                .then(loadRefreshThreshold())
                .doOnSuccess(unused -> logger.info("JWT配置加载完成"))
                .doOnError(error -> logger.info("JWT配置加载失败: {}", error.getMessage()))
                .then();
    }

    /**
     * 加载JWT过期时间配置
     */
    private Mono<Void> loadJwtExpiration() {
        return sysConfigService.getConfigValue("JWT", "EXPIRATION")
                .switchIfEmpty(Mono.just("30")) // 默认30分钟
                .doOnNext(value -> {
                    try {
                        long expirationMinutes = Long.parseLong(value);
                        Jwt.setJwtExpiration(expirationMinutes);
                        logger.debug("JWT过期时间设置为: {} 分钟", expirationMinutes);
                    } catch (NumberFormatException e) {
                        logger.debug("JWT过期时间配置值无效，使用默认值30分钟: {}", value);
                        Jwt.setJwtExpiration(30);
                    }
                })
                .onErrorResume(error -> {
                    logger.info("读取JWT过期时间配置失败，使用默认值30分钟: {}", error.getMessage());
                    Jwt.setJwtExpiration(30);
                    return Mono.just("30");
                })
                .then();
    }

    /**
     * 加载JWT刷新阈值配置
     */
    private Mono<Void> loadRefreshThreshold() {
        return sysConfigService.getConfigValue("JWT", "REFRESH_THRESHOLD")
                .switchIfEmpty(Mono.just("10")) // 默认10分钟
                .doOnNext(value -> {
                    try {
                        long thresholdMinutes = Long.parseLong(value);
                        Jwt.setRefreshThreshold(thresholdMinutes);
                        logger.debug("JWT刷新阈值设置为: {} 分钟", thresholdMinutes);
                    } catch (NumberFormatException e) {
                        logger.info("JWT刷新阈值配置值无效，使用默认值10分钟: {}", value);
                        Jwt.setRefreshThreshold(10);
                    }
                })
                .onErrorResume(error -> {
                    logger.info("读取JWT刷新阈值配置失败，使用默认值10分钟: {}", error.getMessage());
                    Jwt.setRefreshThreshold(10);
                    return Mono.just("10");
                })
                .then();
    }

    @Override
    public int getOrder() {
        return 0; // 最高优先级
    }
} 